// Learn cc.Class:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/class.html
//  - [English] http://www.cocos2d-x.org/docs/creator/en/scripting/class.html
// Learn Attribute:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/reference/attributes.html
//  - [English] http://www.cocos2d-x.org/docs/creator/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/life-cycle-callbacks.html
//  - [English] http://www.cocos2d-x.org/docs/creator/en/scripting/life-cycle-callbacks.html
 /**
  * 倒计时组件
  */


cc.Class({
    extends: cc.Component,

    properties: {
        isInited:false,
        cdLabel:cc.Node,
        //是否正在倒计时
        isCounting:false,
        totalTime:0,
    },

    init(cd){
        if(this.isInited)
            return ;
        this.cdLabel = cd ;
        this.reset();
        this.isInited = true;
    },

    reset(){
        this.cdLabel.getComponent(cc.Label).string = ""
        this.cdLabel.stopAllActions();
        this.isCounting = false;
        this.totalTime = 0;
    },
    //开始倒计时
    //time 倒计时总时间
    // cb 每一秒的回调
    // finishCb 结束时候的回调
    // offset 时间间隔
    // showType 时间显示格式
    startCountDown(time,cb,finishCb,offset = 1.0,showType = 0){

        if(!this.isInited || this.isCounting || time <= 0)
            return 
        this.totalTime = time;
        let delayTime = cc.delayTime(1.0);
        let onFinish = ()=>{
            this.totalTime--;
            if(this.totalTime <= 0)
            {
                this.reset();
                if(finishCb)
                {
                    finishCb();
                }
                return ;
            }
            else
            {
                this.showTime(this.totalTime,showType);
                if(cb)
                {
                    cb();
                }
            }
        }
        this.showTime(this.totalTime,showType);
        this.cdLabel.runAction(cc.repeatForever(cc.sequence(delayTime,cc.callFunc(onFinish))));
        this.isCounting = true;
    },

    showTime(time,type = 0){
       let label =  this.cdLabel.getComponent(cc.Label)
        if(type == 0)
        {
            label.string = time;
        }
        else if(type == 1)
        {
           let h = Math.floor(time / 3600);
           let min = Math.floor((time - h*3600) / 60) ;
           let sec = time - h *3600 - min * 60;
           min = min < 10 ? "0" + min : min;
           sec = sec < 10 ? "0" + sec : sec;
           let str =""
            if(h <= 1)
            {
               str = min + ":" + sec;
            }
            else if(h > 0 && h < 10)
            {
                h = "0" + h;
               str =  h + ":" + min +":" + sec;
            }
          
            cc.log(str);
            label.string = str;
        }
    },
    // 强制停止倒计时
    stopCountDown(){
        this.reset();
    }


});
